package 学生成绩查询管理系统.功能;

import 学生成绩查询管理系统.界面.Login;
import 学生成绩查询管理系统.界面.StudentFrame;
import 学生成绩查询管理系统.界面.StudentSystem;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.*;

public class StudentInquirey extends JFrame implements ActionListener {
    private JMenuItem reLogin;
    private JMenuItem menu;
    private JMenuItem exit;
    private JMenuItem aboutMe;
//    String path = "C:\\Users\\23513\\Desktop\\学生成绩管理系统\\";
    private static final String URL = "jdbc:mysql://localhost:3306/studentmanager";
    private static final String USERNAME = "root";
    private static final String PASSWORD = "123456";

    private static Connection connection;
    private DefaultTableModel tableModel;
    private JTable dataTable;

    public StudentInquirey() {
        initializeDatabase();
        initializeMainFrame();
        queryRecords(); // Auto-load data from the database upon initializing the main frame
        initMenu();
    }

    // 初始化数据库连接
    private void initializeDatabase() {
        try {
            connection = DriverManager.getConnection(URL, USERNAME, PASSWORD);
        } catch (SQLException e) {
            e.printStackTrace();
            JOptionPane.showMessageDialog(this, "无法连接到数据库", "错误", JOptionPane.ERROR_MESSAGE);
            System.exit(1);
        }
    }

    // 初始化主界面
    private void initializeMainFrame() {
        setTitle("成绩管理界面");
        setSize(600, 450);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setLocationRelativeTo(null);
        ImageIcon imageIcon = new ImageIcon( "imge\\Login1.2.png");
        JLabel label = new JLabel(imageIcon);
        this.getContentPane().add(label, BorderLayout.CENTER);

        Toolkit tk = Toolkit.getDefaultToolkit();
        java.awt.Image img = tk.getImage("imge\\成绩录入2.png");
        this.setIconImage(img);

        // 创建表格模型和表格
        tableModel = new DefaultTableModel();
        tableModel.addColumn("ID");
        tableModel.addColumn("姓名");
        tableModel.addColumn("课程");
        tableModel.addColumn("成绩");

        dataTable = new JTable(tableModel);

        // 创建按钮面板
        JPanel buttonPanel = new JPanel();

        // Only keep the "显示数据" (Display Data) button
        JButton displayButton = new JButton("显示数据");

        // Add the query input field and query button
        JTextField idTextField = new JTextField(10);
        JButton queryButton = new JButton("查询");

        // 添加按钮点击事件监听器
        displayButton.addActionListener(e -> showDisplayDataDialog());
        queryButton.addActionListener(e -> queryRecordsById(idTextField.getText()));

        // 将按钮添加到按钮面板
        buttonPanel.add(displayButton);
        buttonPanel.add(new JLabel("ID: "));
        buttonPanel.add(idTextField);
        buttonPanel.add(queryButton);

        // 添加按钮面板和表格到主界面
        add(buttonPanel, BorderLayout.NORTH);
        add(new JScrollPane(dataTable), BorderLayout.CENTER);
    }

    // 显示显示数据的对话框
    private void showDisplayDataDialog() {
        queryRecords();
    }

    // 查询数据库中的记录
    private void queryRecords() {
        try {
            Statement statement = connection.createStatement();
            ResultSet resultSet = statement.executeQuery("SELECT * FROM score");

            // Clear the table model
            tableModel.setRowCount(0);

            // Populate the table model with data from the database
            while (resultSet.next()) {
                Object[] rowData = {
                        resultSet.getInt("ID"),
                        resultSet.getString("name"),
                        resultSet.getString("course"),
                        resultSet.getDouble("score")
                };
                tableModel.addRow(rowData);
            }

            // Close resources
            resultSet.close();
            statement.close();
        } catch (SQLException e) {
            e.printStackTrace();
            JOptionPane.showMessageDialog(this, "查询数据失败", "错误", JOptionPane.ERROR_MESSAGE);
        }
    }

    private void initMenu() {
        JMenuBar jMenuBar = new JMenuBar();
        JMenu about = new JMenu("关于我");
        JMenu function = new JMenu("功能");
        aboutMe = new JMenuItem("QQ二维码");
        reLogin = new JMenuItem("重新登录");
        menu = new JMenuItem("主页");
        exit = new JMenuItem("退出");

        about.add(aboutMe);
        function.add(reLogin);
        function.add(menu);
        function.add(exit);

        aboutMe.addActionListener(this);
        reLogin.addActionListener(this);
        menu.addActionListener(this);
        exit.addActionListener(this);

        jMenuBar.add(about);
        jMenuBar.add(function);
        this.setJMenuBar(jMenuBar);
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        // 获取当前被点击的条目对象
        Object obj = e.getSource();
        if (obj == reLogin) {
            dispose();
            new Login();
        } else if (obj == menu) {
            dispose();
            new StudentFrame();
        } else if (obj == exit) {
            System.exit(0);
        } else if (obj == aboutMe) {
            // 创建一个弹框对象
            JDialog jDialog = new JDialog();
            Toolkit tk = Toolkit.getDefaultToolkit();
            Image img = tk.getImage("imge\\成绩录入2.png");
            jDialog.setIconImage(img);
            // 创建一个管理图片的容器对象JLabel
            JLabel jLabel = new JLabel(new ImageIcon("imge\\about.png"));
            // 设置位置和宽高
            jLabel.setBounds(0, 0, 300, 380);
            // 把图片添加到弹框当中
            jDialog.getContentPane().add(jLabel);
            // 给弹框设置大小
            jDialog.setSize(400, 400);
            // 让弹框置顶
            jDialog.setAlwaysOnTop(true);
            // 让弹框居中
            jDialog.setLocationRelativeTo(null);
            // 弹框不关闭则无法操作下面的界面
            jDialog.setModal(true);
            // 让弹框显示出来
            jDialog.setVisible(true);
        }

    }
    // 查询数据库中的记录，根据ID查询
    private void queryRecordsById(String id) {
        try {
            int idToQuery = Integer.parseInt(id);
            Statement statement = connection.createStatement();
            ResultSet resultSet = statement.executeQuery("SELECT * FROM score WHERE ID=" + idToQuery);

            // Clear the table model
            tableModel.setRowCount(0);

            // Populate the table model with data from the database
            while (resultSet.next()) {
                Object[] rowData = {
                        resultSet.getInt("ID"),
                        resultSet.getString("name"),
                        resultSet.getString("course"),
                        resultSet.getDouble("score")
                };
                tableModel.addRow(rowData);
            }

            // Close resources
            resultSet.close();
            statement.close();
        } catch (NumberFormatException | SQLException e) {
            e.printStackTrace();
            JOptionPane.showMessageDialog(this, "查询数据失败", "错误", JOptionPane.ERROR_MESSAGE);
        }
    }

    // 主方法，启动Swing应用程序
    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            StudentInquirey scoreManager = new StudentInquirey();
            scoreManager.setVisible(true);
        });
    }
}
